/**
 * 功能: 分页工具类  create by ronghui.xiao @2015-11-18
 *
 * @param config
 *
 * config参数说明:
 *
 * callbackMethodName        //调用后台action的js函数名称,可以为字符串或函数名引用,建议使用字符串   (必填)
 * pageSize                  //每页显示的条数   (可选参数)
 * prevBtnID                 //上一页按钮的ID   (可选参数)
 * nextBtnID                 //下一页按钮的ID   (可选参数)
 * firstPageBtnID            //首页按钮的ID   (可选参数)
 * lastPageBtnID             //尾页按钮的ID   (可选参数)
 * pageCodeLayerID           //显示123456789页码的层的ID   (可选参数)
 * jumpPageCodeInputID       //输入跳转页码的文本框的ID   (可选参数)
 * jumpPageBtnID             //跳转页面按钮的ID   (可选参数)
 * showCurrentPageLayerID    //显示当前是第几页的层的ID   (可选参数)
 * showRecordCountLayerID    //显示总记录条数的层的ID   (可选参数)
 * showPageCountLayerID      //显示总页数的层的ID   (可选参数)
 * showNoRecordLayerID       //显示没有信息层的ID   (可选参数)
 * showLoadingLayerID        // 显示正在加载层的ID   (可选参数)
 * recordListLayerID         //显示数据列表层的ID   (必填)
 * isLoop:                   //是否开启循环,默认为false,若为true,当最后一页的时候,点下一页会跳转回第一页   (可选参数)
 * loopThreshold :           //循环的阀值,加入你的总条数为100条,但你想在第50条的时候点击下一页回到第一页,则可以设置此参数   (可选参数)
 * alwaysAppend : true       //当设置此参数为true的时候,你点击上一页或下一页,将不会清空列表,总是追加数据,用在手机端比较合适   (可选参数)
 * pageSizeSelectLayerID     //单选下拉列表层的ID,当你需要使用单选下拉列表来选择页面大小的时候,设置此ID,默认10,20,30
 * pageSizeArray             //该值是一个数组,当你不喜欢默认的10,20,30的页面的时候,你可以自定义一个页码数组
 * cachePagingAndSearchParamsLayerID   //传入一个隐藏域的ID,当你跳转别的页面的时候我会把你的分页参数和查询参数缓存起来,以便回到上次停留的页面.
 *                                       返回的时候使用history.go(-1);
 * searchParams             //当你第一次进入列表想要有初始的查询参数的时候,请传入该值,object类型
 * pagingToolbarLayerID             //分页工具栏的层(传入该ID,会在没有记录的时候隐藏分页工具栏)
 * hideColumnLayerID                 //选择隐藏某些列的层
 *
 * 注:
 *   1.该工具类绑定事件的时候依赖于jquery,使用的时候请先引入jquery
 *   2.新建分页实例示例:
 *      var pagingTooler = new  PagingTooler({
 *            callbackMethodName : "",
 *            pageSize :　
 *            ....
 *      });
 *   3.若该工具类不满足某些需求的时候,可以扩展你自己需要的方法,例如 this.yourFunctionName = function(){....}或者继承该类,重写某些方法
 */
function PagingTooler(config){

    /*若配置不是对象,直接返回*/
    if(typeof config != "object") return;

    /*固有属性*/
    this.pageSize = 10;
    this.currentPage = 1;
    this.recordCount = 0;
    this.pageCount = 0;

    /*config中的属性都存入this中*/
    for(var key in config){
        this[key] = config[key];
    }

    /*从缓存中读取分页参数和查询参数*/
    if(this.cachePagingAndSearchParamsLayerID){
        if(this.cachePagingAndSearchParamsLayerID){
            var params = PagingTooler.prototype.parseParamsStrToObject($("#" + this.cachePagingAndSearchParamsLayerID).val());
            if(params.pageSize && params.page){
                this.pageSize = params.pageSize;
                this.currentPage = params.page;
                delete params.pageSize;
                delete params.offset;
                delete params.page;
                this.searchParams = params;
                this.isCaseParams = true;    //标志该分页实例参数被缓存过
                /*回到顶部*/
                if(parent){
                    parent.window.scrollTo(0,0);
                }else{
                    window.scrollTo(0,0);
                }
            }
        }
    }

    /*初始化*/
    this.init = function(pageSize){
        this.pageSize = pageSize;
        this.currentPage = 1;
        this.recordCount = 0;
        this.pageCount = 0;
    };

    /*获取表头name-序号的map*/
    this.getTitleIndexMap = function(){

        if(this.titleIndexMap) return this.titleIndexMap;

        var jqRecordListLayer =  $("#" + currentInstance.recordListLayerID);

        /*隐藏相关的列*/
        var theadThs = jqRecordListLayer.parent("table").find("thead").find('tr>th,tr>td');

        var titleIndexMap = {};

        for(var i = 0 ; i < theadThs.length ; i ++){
            var item = $(theadThs[i]);
            titleIndexMap[item.text()] = i + 1;
        };

        if(theadThs.length > 0){
            this.titleIndexMap = titleIndexMap;
        }

        return titleIndexMap;

    };

    /*获取起始位置*/
    this.getCurrentOffset = function(){
        return  ((this.currentPage - 1) * this.pageSize);
    };

    /*获取分页参数*/
    this.getPageOffsetPagesize = function(){
        return {pageNum : this.currentPage, pageSize: this.pageSize , offset : this.getCurrentOffset()};
    };

    /*获取分页和查询参数*/
    this.getPagingAndSearchParams = function(){
        var params = this.getPageOffsetPagesize();
        if(this.searchParams && typeof this.searchParams == "object"){
            for(var key in this.searchParams){
                var value = this.searchParams[key];
                if(value && value != ""){
                    params[key] = value;
                }
            }
        }
        return params;
    };

    /*获取查询参数*/
    this.getSearchParams = function(){
        return this.searchParams;
    };

    /*回调传入的方法*/
    this.callback = function(){
        this.hideSloganAndRecordList();
        this.showLoadingSlogan();  //显示加载标语
        if(typeof this.callbackMethodName == "string"){
            eval(this.callbackMethodName + "();");
        }else if(typeof this.callbackMethodName == "function"){
            this.callbackMethodName();
        }
    };

    /*设置总记录数*/
    this.setRecordCount = function(recordCount){

        this.hideSloganAndRecordList();                     //隐藏所有标语和记录列表

        if(recordCount && recordCount > 0){
            this.setRecordCountPageCount(recordCount);      // 设置总记录数和总页数
            this.setRecordCountByLoopThreshold();           //若阀值小于总记录数,则使用阀值
            this.switchPageCode(this.curPageCodeCss);       //切换页码
            this.appendTxtToRecordListLayer(this.txt);      //插入文本
            this.showPagingParams();                        //显示分页参数
            this.showPagingToolerBar();
            this.cachePagingAndSearchParams();              //缓存查询和分页参数
        }else{
            /*清除页面显示参数*/
            this.cleanPagingParams();
            //若有分页工具栏,则隐藏
            this.hidePagingToolerBar();
            /*显示没有信息的标语*/
            this.showNoRecordSlogan();
        }
    };

    /*设置总记录数和总页数*/
    this.setRecordCountPageCount = function(recordCount){
        if(recordCount && recordCount > 0) {
            this.recordCount = recordCount;
            this.pageCount = parseInt(((this.recordCount - 1) / this.pageSize) + 1); //总页数
        }
    };

    /*根据阀值设置总记录数*/
    this.setRecordCountByLoopThreshold = function(recordCount){
        if(recordCount && recordCount > 0 && this.isLoop && this.loopThreshold && this.recordCount > this.loopThreshold) {
            this.recordCount = this.loopThreshold;
        }
    };

    /*隐藏列复选框选中触发事件*/
    if(this.hideColumnLayerID){
        var  currentInstance = this;
        var jqRecordListLayer =  $("#" + currentInstance.recordListLayerID);
        var jqThead = jqRecordListLayer.parent("table").find("thead");
       

        $("#" +this.hideColumnLayerID).find("input:checkbox").click(function() {

            var isChecked = $(this).is(':checked');
            var titleIndexMap = currentInstance.getTitleIndexMap();

            var text = $(this).parent("label").text();

            var index = titleIndexMap[text];


            if(isChecked){
                jqThead.find("tr>th:nth-child("+index+")").hide();
                jqRecordListLayer.find("tr>td:nth-child("+index+")").hide();
            }else{
                jqThead.find("tr>th:nth-child("+index+")").show();
                jqRecordListLayer.find("tr>td:nth-child("+index+")").show();
            }

        });
    }
    
    /*隐藏不需要展示的列*/
    this.initHideColumns = function(){
    	  
    	   //若未设置,则直接返回
    	   if(!this.hideColumnLayerID) return;
    	  
    	   var  currentInstance = this;
           var jqRecordListLayer =  $("#" + currentInstance.recordListLayerID);
           var jqThead = jqRecordListLayer.parent("table").find("thead");
           
           var jqCheckedHideColumns = $("#" +this.hideColumnLayerID).find("input:checkbox:checked");
           
           var titleIndexMap = currentInstance.getTitleIndexMap();
           for(var i = 0 ; i < jqCheckedHideColumns.length ; i ++){
        	   var jqItem = $(jqCheckedHideColumns[i]);
               var text = jqItem.parent("label").text();
               var index = titleIndexMap[text];
               jqThead.find("tr>th:nth-child("+index+")").hide();
               jqRecordListLayer.find("tr>td:nth-child("+index+")").hide();
           }
           
    }

    /*上一页按钮绑定事件*/
    if(this.prevBtnID){
        var  currentInstance = this;
        $("#" + currentInstance.prevBtnID).click(function(e){
            /*若不是第一页*/
            if( currentInstance.currentPage > 1){
                currentInstance.currentPage --;
                currentInstance.callback();
            }

            /*若是第一页且总页数要大于1,则回到最后一页*/
            else if (currentInstance.isLoop && currentInstance.currentPage == 1 && currentInstance.pageCount > 1){
                currentInstance.currentPage = currentInstance.pageCount;
                currentInstance.callback();
            }
        });
    }

    /*下一页按钮绑定事件*/
    if(this.nextBtnID){
        var  currentInstance = this;
        $("#" + currentInstance.nextBtnID).click(function(e){
            /*若不是最后一页,进入下一页*/
            if( currentInstance.currentPage < currentInstance.pageCount){
                currentInstance.currentPage ++;
                currentInstance.callback();
            }

            /*若是最后一页,回到第一页*/
            else if(currentInstance.isLoop && currentInstance.currentPage != 1 && currentInstance.currentPage == currentInstance.pageCount){
                currentInstance.currentPage = 1;
                currentInstance.callback();
            }
        });
    }


    /*首页按钮绑定事件*/
    if(this.firstPageBtnID){
        var  currentInstance = this;
        $("#" + currentInstance.firstPageBtnID).click(function(e){
            if(currentInstance.pageCount > 1){
                currentInstance.currentPage = 1;
                currentInstance.callback();
            }
        });
    }

    /*最后一页按钮绑定事件*/
    if(this.lastPageBtnID){
        var  currentInstance = this;
        $("#" + currentInstance.lastPageBtnID).click(function(e){
            if(currentInstance.pageCount != 0 && currentInstance.currentPage != currentInstance.pageCount){
                currentInstance.currentPage = currentInstance.pageCount;
                currentInstance.callback();
            }
        });
    }

    /*跳转按钮和页码文本框绑定事件*/
    if(this.jumpPageCodeInputID && this.jumpPageBtnID){
        var  currentInstance = this;

        /*跳转页码只能是数字*/
        $("#" + currentInstance.jumpPageCodeInputID).keyup(function(e){
            var value = e.target.value;
            e.target.value = value.replace(/[^0-9]/g,'');
        });

        /*跳转按钮触发事件*/
        $("#" + currentInstance.jumpPageBtnID).click(function(e){
            var pageCode = document.getElementById(currentInstance.jumpPageCodeInputID).value;
            if(!isNaN(pageCode) && pageCode > 0 && pageCode <= currentInstance.pageCount){
                currentInstance.currentPage = pageCode;
                currentInstance.callback();
            }
        });
    }

    /*选择页面大小绑定事件*/
    if(this.pageSizeSelectLayerID){

        var currentInstance = this;
        var optionTxt = "";
        if(currentInstance.pageSizeArray && currentInstance.pageSizeArray.length > 0){
            var pageSizeArray = currentInstance.pageSizeArray;
            for(var i = 0 ; i < pageSizeArray.length ; i ++){
                var size = pageSizeArray[i];
                if(!isNaN(size)){
                    optionTxt += '<option value="'+size+'">显示'+size+'行</option>';
                }
            }
            if(!currentInstance.isCaseParams) currentInstance.pageSize = pageSizeArray[0];
        }

        if(optionTxt == ""){
            for(var i = 1 ; i <= 3 ; i++){
                optionTxt += '<option value="'+currentInstance.pageSize+'">显示'+currentInstance.pageSize+'行</option>';;
            }
        }
        
        $("#" + this.pageSizeSelectLayerID).html(optionTxt).change(function(e){
            var target = e.target;
            currentInstance.pageSize = target.value;
            currentInstance.currentPage = 1;
            currentInstance.callback();
        }).find("option[value="+this.pageSize+"]").attr("selected","selected");

    }

    /*插入页码*/
    if(this.pageCodeLayerID){

        var currentInstance = this;

        /*页码文本*/
        var txt = '<a href="javascript:void(0);"  name="page1" class="btn btn-primary" style="display:none;">1</a>'+
            '<a href="javascript:void(0);"  name="page2" class="btn btn-primary" style="display:none;">2</a>'+
            '<a href="javascript:void(0);"  name="page3" class="btn btn-primary" style="display:none;">3</a>'+
            '<a href="javascript:void(0);"  name="page4" class="btn btn-primary" style="display:none;">4</a>'+
            '<a href="javascript:void(0);"  name="page5" class="btn btn-primary" style="display:none;">5</a>'+
            '<a href="javascript:void(0);"  name="page6" class="btn btn-primary" style="display:none;">6</a>'+
            '<a href="javascript:void(0);"  name="page7" class="btn btn-primary" style="display:none;">7</a>'+
            '<a href="javascript:void(0);"  name="page8" class="btn btn-primary" style="display:none;">8</a>'+
            '<a href="javascript:void(0);"  name="page9" class="btn btn-primary" style="display:none;">9</a>';

        /*把文本插入指定位置*/
        var pageCodeLayer = $("#" + currentInstance.pageCodeLayerID);
        pageCodeLayer.html(txt);

        /*给页码绑定点击事件*/
        pageCodeLayer.find("a").each(function(){
            $(this).click(function(e){
                var pageCode = e.target.innerHTML;
                if(currentInstance.currentPage != pageCode){
                    currentInstance.currentPage = pageCode;
                    currentInstance.callback();
                }
            });
        });
    }

    /*删除或更新后停留在当前页*/
    this.freshPageByDelete = function(){

        /*若是最后一页且只有1条的时候*/
        if(((this.currentPage - 1) * this.pageSize + 1) == this.recordCount){
            if(this.currentPage > 1){
                this.currentPage --;
            }
        }
        this.callback();
    };

    /*根据总记录数,文本,页面高亮样式在页面显示*/
    this.showInPage = function(recordCount,txt,curPageCodeCss){
        this.recordCount = recordCount;
        this.txt = txt;
        this.curPageCodeCss = curPageCodeCss;
        this.setRecordCount(this.recordCount);
    };

    /*切换页码*/
    this.switchPageCode = function(curPageCodeCss){
        if(this.pageCodeLayerID && this.recordCount && this.recordCount > 0){
            var pageCode = this.currentPage;
            var pageCount = this.pageCount;
            var pagemin=pageCode-4;
            if (pagemin<1) pagemin=1;
            var pagemax=pagemin+8;
            if (pagemax>pageCount) pagemax=pageCount;
            if (pagemax<(pagemin+8) && pagemin>1) pagemin=pagemin-1;
            if (pagemax<(pagemin+8) && pagemin>1) pagemin=pagemin-1;
            if (pagemax<(pagemin+8) && pagemin>1) pagemin=pagemin-1;
            if (pagemax<(pagemin+8) && pagemin>1) pagemin=pagemin-1;
            var pageCodeLayer = $("#" + this.pageCodeLayerID);
            pageCodeLayer.find("a").each(function(){
                var currentElement = $(this);
                if (pagemin<=pagemax) {
                    currentElement.html(pagemin);
                    currentElement.show();
                    if (pagemin==pageCode){
                        if(curPageCodeCss){
                            currentElement.addClass(curPageCodeCss);
                        }else{
                            currentElement.css("color","#FF8D34");
                        }
                    }else{
                        if(curPageCodeCss){
                            currentElement.removeClass(curPageCodeCss);
                        }else{
                            currentElement.css("color","");
                        }
                    }
                }
                else{
                    currentElement.hide();
                }
                pagemin=pagemin+1;
            });
        }
    };

    /*在页面显示分页参数*/
    this.showPagingParams = function(){
        var currentInstance = this;
        if(currentInstance.pageCodeLayerID){
            $("#" + currentInstance.pageCodeLayerID).show();
        }
        if(currentInstance.showCurrentPageLayerID){
            $("#" + currentInstance.showCurrentPageLayerID).html(this.currentPage);
        }
        if(currentInstance.showRecordCountLayerID){
            $("#" + currentInstance.showRecordCountLayerID).html(this.recordCount);
        }
        if(currentInstance.showPageCountLayerID){
            $("#" + currentInstance.showPageCountLayerID).html(this.pageCount);
        }
    };

    /*在页面清空分页参数*/
    this.cleanPagingParams = function(){
        var currentInstance = this;
        if(currentInstance.pageCodeLayerID){
            $("#" + currentInstance.pageCodeLayerID).hide();
        }
        if(currentInstance.showCurrentPageLayerID){
            $("#" + currentInstance.showCurrentPageLayerID).html("");
        }
        if(currentInstance.showRecordCountLayerID){
            $("#" + currentInstance.showRecordCountLayerID).html("");
        }
        if(currentInstance.showPageCountLayerID){
            $("#" + currentInstance.showPageCountLayerID).html("");
        }
    };

    /*显示没有信息的标语*/
    this.showNoRecordSlogan = function(){
        var currentInstance = this;
        if(currentInstance.showNoRecordLayerID){
            $("#" + currentInstance.showNoRecordLayerID).show();
        }
    };

    /*隐藏没有信息的标语*/
    this.hideNoRecordSlogan = function(){
        var currentInstance = this;
        if(currentInstance.showNoRecordLayerID){
            $("#" + currentInstance.showNoRecordLayerID).hide();
        }
    };

    /*显示正在加载的标语*/
    this.showLoadingSlogan = function(){
        var currentInstance = this;
        if(currentInstance.showLoadingLayerID){
        	this.hidePagingToolerBar(); //分页工具栏隐藏,不然很丑
            $("#" + currentInstance.showLoadingLayerID).show();
        }
    };

    /*隐藏正在加载的标语*/
    this.hideLoadingSlogan = function(){
        var currentInstance = this;
        if(currentInstance.showLoadingLayerID){
            $("#" + currentInstance.showLoadingLayerID).hide();
        }
    };
    
    /*显示分页工具栏*/
    this.showPagingToolerBar = function(){
        var currentInstance = this;
        if(currentInstance.pagingToolbarLayerID){
            $("#" + currentInstance.pagingToolbarLayerID).show();
        }
    };
    
    /*隐藏分页工具栏*/
    this.hidePagingToolerBar = function(){
        var currentInstance = this;
        if(currentInstance.pagingToolbarLayerID){
            $("#" + currentInstance.pagingToolbarLayerID).hide();
        }
    };

    /*把记录列表添加进列表显示层*/
    this.appendTxtToRecordListLayer = function(txt){
    	
        var currentInstance = this;

        if(currentInstance.recordListLayerID && txt){
        	
            var jqRecordListLayer =  $("#" + currentInstance.recordListLayerID);
            
            //隐藏列的层
            var jqHideColumnLayer = $("#" + currentInstance.hideColumnLayerID);
            
            //若没有隐藏列的功能 , 则直接返回
            if(jqHideColumnLayer.length == 0 ){
	        	  jqRecordListLayer.html(txt).show();
	        	  return;
            }
            
            jqRecordListLayer.hide().html(txt);
            
            /*隐藏相关的列*/
            var theadThs = jqRecordListLayer.parent("table").find('thead>tr>th,thead>tr>td');
            var exportConf = {};

            for(var i = 0 ; i < theadThs.length ; i ++){
                var item = $(theadThs[i]);
                if(!item.is(":visible")){
                    exportConf[i] = true;
                }
            };

            for(var key in exportConf){
                var index = parseInt(key) + 1;
                jqRecordListLayer.find("tr>td:nth-child("+(index)+")").hide();
            }

            jqRecordListLayer.show();

        }

    };

    /*清空记录列表*/
    this.cleanRecordList = function(){
        var currentInstance = this;
        if(currentInstance.recordListLayerID && !this.alwaysAppend){
            $("#" + currentInstance.recordListLayerID).html("");
        }
    };

    /*隐藏所有标语和记录列表*/
    this.hideSloganAndRecordList = function(){
        this.hideLoadingSlogan();
        this.hideNoRecordSlogan();
        this.cleanRecordList();
    };
    
    /*设置查询参数*/
    this.search = function(searchParams){
        if(typeof searchParams != "object") return;
        this.searchParams = searchParams;
        this.currentPage = 1;
        this.callback();
    };

    /*验证是否最后一页*/
    this.isLastPage = function(){
        if(this.pageCount == 0  || this.currentPage == this.pageCount){
            return true;
        }
        return false;
    };

    /*缓存分页参数和查询参数*/
    this.cachePagingAndSearchParams = function(){
        var currentInstance = this;
        if(currentInstance.cachePagingAndSearchParamsLayerID){
            var params = currentInstance.getPagingAndSearchParams();
            var paramsTxt = PagingTooler.prototype.parseObjectToParamsStr(params);
            $("#" + currentInstance.cachePagingAndSearchParamsLayerID).val(paramsTxt);
        }
    };

    /*读取缓存的参数来初始化当前分页实例的参数*/
    this.iniParamsFromParamsLayer = function(){
        var currentInstance = this;
        if(currentInstance.cachePagingAndSearchParamsLayerID){
            var params = PagingTooler.prototype.parseParamsStrToObject($("#" + currentInstance.cachePagingAndSearchParamsLayerID).val());
            if(params.pageSize && params.page){
                currentInstance.pageSize = params.pageSize;
                currentInstance.currentPage = params.page;
                delete params.pageSize;
                delete params.offset;
                delete params.page;
                currentInstance.searchParams = params;
            }
        }
    };
    
    //初始化表格
    this.initTableList = function(){
    	
    	//初始化不需要展示的列
    	 this.initHideColumns();
    	
    	//调用查询方法
    	this.callback();
    }
    
}

/*把对象转化成&连接的字符串*/
PagingTooler.prototype.parseObjectToParamsStr = function(obj){
    var paramsTxt = "";
    if(obj  && typeof obj == "object"){
        for(var key in obj){
            paramsTxt += "&" + key + "=" + obj[key];
        }
        if(paramsTxt.length > 0) paramsTxt = paramsTxt.substring(1);
    }
    return paramsTxt;
};

/*把&连接的参数字符串连接的字符串转化为对象*/
PagingTooler.prototype.parseParamsStrToObject = function(paramsStr){
    var obj = {};
    if(paramsStr && paramsStr.length > 0 && paramsStr.indexOf("&") != -1){
        var arr =  paramsStr.split("&");
        for(var i = 0 ; i < arr.length ; i ++){
            var itemArr = arr[i].split("=");
            obj[itemArr[0]] = itemArr[1];
        }
    }
    return obj;
};